import Config from './config.js'

export default {
	methods: {
		sendRequest(params) {
			let method = params.data != undefined ? 'POST' : 'GET', // 请求方式
				url = Config.baseUrl + '/api.php?method=' + params.url, // 请求路径
				data = {
					token: uni.getStorageSync('token'),
					private_key: Config.privateKey,
					is_uniapp: 1,
					// #ifdef H5
					is_h5: 1,
					domain: Config.shareDomain,
					// #endif
					// #ifdef MP
					is_applet: 1,
					// #endif
				};
			// 参数
			if (params.data != undefined) Object.assign(data, params.data);

			if (params.async === false) {
				//同步
				return new Promise((resolve, reject) => {
					uni.request({
						url: url,
						method: method,
						data: data,
						header: params.header || {
							'content-type': 'application/x-www-form-urlencoded;application/json'
						},
						dataType: params.dataType || 'json',
						responseType: params.responseType || 'text',
						success: (res) => {
							resolve(JSON.parse(res.data));
						},
						fail: (res) => {
							reject(res);
						},
						complete: (res) => {
							reject(res);
						}
					});
				});
			} else {
				//异步
				uni.request({
					url: url,
					method: method,
					data: data,
					header: params.header || {
						'content-type': 'application/x-www-form-urlencoded;application/json'
					},
					dataType: params.dataType || 'json',
					responseType: params.responseType || 'text',
					success: (res) => {
						typeof params.success == 'function' && params.success(JSON.parse(res.data));
					},
					fail: (res) => {
						typeof params.fail == 'function' && params.fail(res);
					},
					complete: (res) => {
						typeof params.complete == 'function' && params.complete(res);
					}
				});
			}
		}
	}
}
